<?php
/**
 * Created by PhpStorm.
 * User: chaichunmin
 * Date: 2017/1/5
 * Time: 13:55
 */

namespace SDXApi\Behaviors;
use Think\Behavior;

class LouxiaoerOrderBehavior extends Behavior {

    public function run(&$order_id){

        $louxiaoer_order = D('LouxiaoerOrder')->getLouxiaoerOrderByOrderId($order_id);
        if($louxiaoer_order){
             echo '已绑定楼小二';
            return;
        }

        $data = D('LouxiaoerOrder')->findOrderInLouxiaoerLandmark($order_id);

        if(!$data){
            echo '未找到订单数据';
            return;
        }

        //未找到相应地标
        if(!$data['id']){

            if(!$data['region_id']){
                //echo '订单没有区域信息';
                return;
            }

            //获取地标，没有地标用地址
            $sign_building = $data['sign_building'] ? $data['sign_building'] : $data['address'];
            $landmark = D('LouxiaoerLandmark')->findLandmarkByName($sign_building, $data['region_id']);

            if($landmark){
                $data['id'] = $landmark['id'];
            }else{
                //写入地标（地点地址）
                $data['id'] = D('LouxiaoerLandmark')->addLandmark($sign_building, $data['region_id'], $data['wdtype']);
            }

        }


        $louxiaoer_user_id = 0;
        $louxiaoer = array();
        if($data['louxiaoer_id']){
            $binding_louxiaoer_time = gmtime();
            $created = '系统分配';

            //添加楼小二用户
            $louxiaoer = D('LouxiaoerUser')->findLouxiaoerUser($data['louxiaoer_id'], $data['user_id'], $data['address_id']);
            if(!$louxiaoer){
                $louxiaoer_user_id = D('LouxiaoerUser')->addLouxiaoerUser($data['louxiaoer_id'], $data['user_id'], $data['address_id'], $data['id']);
            }else{
                $louxiaoer_user_id = $louxiaoer['id'];
            }

        }else{
            $binding_louxiaoer_time = 0;
            $created = '';
        }


        $data['louxiaoer_id'] = $data['louxiaoer_id'] ? $data['louxiaoer_id'] : 0;

        //订单绑定楼小二
        D('LouxiaoerOrder')->orderBindingLouxiaoer($louxiaoer_user_id, $data['user_id'], $data['address_id'], $data['id'], $data['order_id'], $data['louxiaoer_id'], $binding_louxiaoer_time, $created);


        return;
    }

}